<script setup>
    import reserveApi from "@/api/reserve.js";
    import courseApi from "@/api/course.js";
    import {ref, onMounted} from "vue";
    import {ElMessage, ElMessageBox} from "element-plus";
    import {useTokenStore} from '@/store/token.js'
    
    const tokenStore = useTokenStore()
    
    //数据表格
    const list = ref([])
    const total = ref(0)
    //分页信息和搜索条件
    const reserveQuery = ref({
        courseId:'',
        userId:'',
        page:1,
        limit:10
    })

    // 下拉框数据
    const courses = ref([])

    const loadData = () =>{
        // 用户端只显示当前用户的预约
        console.log('loadData - tokenStore.userId:', tokenStore.userId)
        console.log('loadData - tokenStore.token:', tokenStore.token)
        
        const userId = tokenStore.userId
        if (!userId) {
            console.error('无法获取当前用户ID，tokenStore内容:', tokenStore)
            ElMessage.error('用户身份验证失败，请重新登录')
            return
        }
        console.log('加载用户预约数据，用户ID:', userId)
        reserveQuery.value.userId = userId
        console.log('发送请求参数:', reserveQuery.value)
        reserveApi.list(reserveQuery.value).then(result=>{
            console.log('预约API响应:', result)
            if (result.code == 0){
                list.value = result.data.records
                total.value = result.data.total
                console.log('用户预约数据加载成功:', result.data.records)
            }
        })
    }
    
    // 加载课程数据
    const loadCourses = () => {
        courseApi.list({page: 1, limit: 1000}).then(result => {
            if (result.code == 0) {
                courses.value = result.data.records
            }
        })
    }

    onMounted(() => {
        loadData()
        loadCourses()
    })

    const onSearch = () =>{
        reserveQuery.value.page = 1
        loadData()
    }

    const reset = () =>{
        reserveQuery.value.courseId = ''
    }

    //根据ID取消预约
    const deleteById = (id) =>{
        ElMessageBox.confirm(
            '您确认要取消这个预约吗？',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(() => {
                reserveApi.deleteById(id).then(result =>{
                    if (result.code == 0){
                        ElMessage.success('预约已取消')
                        loadData()
                    }else {
                        ElMessage.error(result.msg)
                    }
                })
            })
    }

    //删除预约记录
    const deleteReserve = (id) => {
        ElMessageBox.confirm(
            '您确认要删除这个预约记录吗？删除后无法恢复！',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(() => {
                reserveApi.deleteById(id).then(result =>{
                    if (result.code == 0){
                        ElMessage.success('预约记录已删除')
                        loadData()
                    }else {
                        ElMessage.error(result.msg)
                    }
                })
            })
    }

    //添加预约
    const dialogFormVisible = ref(false)
    const reserve = ref({})
    const title = ref('')
    const showAddDialog = () =>{
        const userId = tokenStore.userId
        if (!userId) {
            console.error('无法获取当前用户ID')
            ElMessage.error('用户身份验证失败，请重新登录')
            return
        }
        reserve.value = {
            userId: userId
        }
        title.value = '选择课程进行预约'
        dialogFormVisible.value = true
    }

    const addReserve = () =>{
        reserveApi.add(reserve.value).then(result =>{
            if (result.code == 0){
                ElMessage.success(result.msg)
                dialogFormVisible.value = false
                loadData()
            }else {
                ElMessage.error(result.msg)
            }
        })
    }

    // 评分和评论
    const showRateDialog = (row) => {
        reserve.value = {...row}
        title.value = '评分和评论'
        dialogFormVisible.value = true
    }

    const updateRate = () => {
        reserveApi.update(reserve.value).then(result =>{
            if (result.code == 0){
                ElMessage.success(result.msg)
                dialogFormVisible.value = false
                loadData()
            }else {
                ElMessage.error(result.msg)
            }
        })
    }

    // 预约课程
    const reserveCourse = (course) => {
        const userId = tokenStore.userId
        if (!userId) {
            console.error('无法获取当前用户ID')
            ElMessage.error('用户身份验证失败，请重新登录')
            return
        }
        
        ElMessageBox.confirm(
            `您确认要预约课程"${course.name}"吗？`,
            '确认预约',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'info',
            }
        )
            .then(() => {
                const reserveData = {
                    userId: userId,
                    courseId: course.id
                }
                
                reserveApi.add(reserveData).then(result => {
                    if (result.code == 0) {
                        ElMessage.success('预约成功')
                        dialogFormVisible.value = false
                        loadData()
                    } else {
                        ElMessage.error(result.msg)
                    }
                })
            })
    }

    // 格式化时间
    const formatDateTime = (dateTime) => {
        if (!dateTime) return '未设置'
        const date = new Date(dateTime)
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        })
    }

</script>

<template>
    <el-card class="">
        <template #header>
            <div class="header">
                <el-button type="primary" @click="showAddDialog">预约课程</el-button>
            </div>
        </template>
        <el-form :inline="true">
            <el-form-item label="课程">
                <el-select v-model="reserveQuery.courseId" placeholder="请选择课程" clearable style="width: 200px">
                    <el-option 
                        v-for="course in courses" 
                        :key="course.id" 
                        :label="course.name" 
                        :value="course.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">搜索</el-button>
                <el-button type="danger" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="list" style="width: 100%">
            <el-table-column fixed prop="id" label="ID"/>
            <el-table-column prop="courseName" label="课程名称"/>
            <el-table-column prop="courseRoom" label="教室"/>
            <el-table-column prop="courseTime" label="课程时间" width="180px"/>
            <el-table-column prop="score" label="评分"/>
            <el-table-column prop="comment" label="评论"/>
            <el-table-column prop="status" label="状态" width="120px">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                        {{ scope.row.status === 1 ? '已预约' : '已取消' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="预约时间" width="180px"/>
            <el-table-column prop="updateTime" label="更新时间" width="180px"/>
            <el-table-column align="center" width="320px" fixed="right" label="操作">
                <template #default="{ row }">
                    <el-button 
                        size="small" 
                        type="primary" 
                        @click="showRateDialog(row)"
                        class="action-button"
                    >
                        评分
                    </el-button>
                    <el-button 
                        size="small" 
                        type="warning" 
                        @click="deleteById(row.id)"
                        :disabled="row.status === 0"
                        class="action-button"
                    >
                        取消预约
                    </el-button>
                    <el-button 
                        size="small" 
                        type="danger" 
                        @click="deleteReserve(row.id)"
                        class="action-button"
                    >
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            v-model:current-page="reserveQuery.page"
            v-model:page-size="reserveQuery.limit"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @change="loadData"
            style="margin-top: 20px; justify-content: flex-end"
        />
    </el-card>

    <!--添加预约/评分弹出框-->
    <el-dialog v-model="dialogFormVisible" :title="title" width="90%" :lock-scroll="false">
        <!-- 预约课程表单 -->
        <div v-if="!reserve.id">
            <el-table :data="courses" style="width: 100%" max-height="500">
                <el-table-column prop="id" label="ID" min-width="60"/>
                <el-table-column prop="name" label="课程名称" min-width="120"/>
                <el-table-column prop="coachName" label="教练" min-width="100"/>
                <el-table-column prop="room" label="教室" min-width="100"/>
                <el-table-column prop="time" label="课程时间" min-width="160">
                    <template #default="scope">
                        {{ formatDateTime(scope.row.time) }}
                    </template>
                </el-table-column>
                <el-table-column prop="length" label="时长(分钟)" min-width="100"/>
                <el-table-column prop="maxCount" label="最大人数" min-width="100"/>
                <el-table-column prop="status" label="状态" min-width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                            {{ scope.row.status === 1 ? '正常' : '停用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="image" label="封面" min-width="120">
                    <template #default="scope">
                        <img 
                            v-if="scope.row.image" 
                            :src="scope.row.image" 
                            class="course-thumbnail" 
                            alt="课程封面"
                        />
                        <span v-else>无封面</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" min-width="120" fixed="right">
                    <template #default="scope">
                        <el-button 
                            type="primary" 
                            size="small" 
                            @click="reserveCourse(scope.row)"
                            :disabled="scope.row.status === 0"
                        >
                            预约
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        
        <!-- 评分表单 -->
        <div v-else>
            <el-form :model="reserve" label-width="100px">
                <el-form-item label="评分">
                    <el-rate v-model="reserve.score" :max="5" show-score />
                </el-form-item>
                <el-form-item label="评论">
                    <el-input v-model="reserve.comment" type="textarea" :rows="4" autocomplete="off" />
                </el-form-item>
            </el-form>
        </div>
        
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">关闭</el-button>
                <el-button 
                    v-if="reserve.id" 
                    type="primary" 
                    @click="updateRate()"
                >
                    确认评分
                </el-button>
            </div>
        </template>
    </el-dialog>

</template>

<style scoped lang="scss">
.course-thumbnail {
    width: 60px;
    height: 45px;
    object-fit: cover;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
}

// 操作按钮间距
.action-button {
    margin-right: 8px !important;
    
    &:last-child {
        margin-right: 0 !important;
    }
}

.el-table {
    .el-button {
        margin: 0;
    }
}

.el-dialog {
    .el-table {
        margin-top: 0;
        width: 100% !important;
    }
    
    .el-table__body-wrapper {
        width: 100% !important;
    }
    
    .el-table__header-wrapper {
        width: 100% !important;
    }
}

// 确保表格占满整个对话框宽度
:deep(.el-dialog__body) {
    .el-table {
        width: 100% !important;
    }
}

:deep(.el-table) {
    width: 100% !important;
}

:deep(.el-table__body) {
    width: 100% !important;
}

:deep(.el-table__header) {
    width: 100% !important;
}
</style>
